import { PDFExportService } from './pdfExportService';
import { WordExportServiceSimple } from './wordExportServiceSimple';
import { simpleStorageAdapter } from './simpleStorageAdapter';
import { 
  ExportService, 
  ExportResult, 
  ExportProgress, 
  ExportHistoryItem, 
  ExportTemplate,
  PDFExportOptions,
  WordExportOptions,
  EXPORT_STORAGE_KEYS
} from './types';

export class ExportServiceImpl implements ExportService {
  private pdfService: PDFExportService;
  private wordService: WordExportServiceSimple;

  constructor(progressCallback?: (progress: ExportProgress) => void) {
    this.pdfService = new PDFExportService(progressCallback);
    this.wordService = new WordExportServiceSimple(progressCallback);
  }

  /**
   * 导出为PDF
   */
  async exportToPDF(content: string, options: PDFExportOptions, filename?: string): Promise<ExportResult> {
    const result = await this.pdfService.exportToPDF(content, options, filename);
    
    if (result.success) {
      await this.addToHistory({
        id: this.generateId(),
        filename: result.filename!,
        format: 'pdf',
        timestamp: Date.now(),
        size: result.size!,
        options
      });
    }

    return result;
  }

  /**
   * 导出为Word
   */
  async exportToWord(content: string, options: WordExportOptions, filename?: string): Promise<ExportResult> {
    const result = await this.wordService.exportToWord(content, options, filename);
    
    if (result.success) {
      await this.addToHistory({
        id: this.generateId(),
        filename: result.filename!,
        format: 'word',
        timestamp: Date.now(),
        size: result.size!,
        options
      });
    }

    return result;
  }

  /**
   * 预览导出（暂时返回空字符串，后续可实现预览功能）
   */
  async previewExport(_content: string, _format: 'pdf' | 'word', _options: any): Promise<string> {
    // TODO: 实现预览功能
    console.log('[ExportService] 预览功能暂未实现');
    return '';
  }

  /**
   * 获取导出历史
   */
  async getExportHistory(): Promise<ExportHistoryItem[]> {
    try {
      const result = await simpleStorageAdapter.get<ExportHistoryItem[]>(EXPORT_STORAGE_KEYS.EXPORT_HISTORY);
      
      if (result.success && result.data) {
        // 按时间倒序排列
        return result.data.sort((a: ExportHistoryItem, b: ExportHistoryItem) => b.timestamp - a.timestamp);
      }
      
      return [];
    } catch (error) {
      console.error('[ExportService] 获取导出历史失败:', error);
      return [];
    }
  }

  /**
   * 保存导出模板
   */
  async saveExportTemplate(template: ExportTemplate): Promise<void> {
    try {
      const templates = await this.getExportTemplates();
      
      // 检查是否已存在同名模板
      const existingIndex = templates.findIndex(t => t.id === template.id);
      
      if (existingIndex >= 0) {
        // 更新现有模板
        templates[existingIndex] = { ...template, updatedAt: Date.now() };
      } else {
        // 添加新模板
        templates.push(template);
      }

      const result = await simpleStorageAdapter.set(EXPORT_STORAGE_KEYS.CUSTOM_TEMPLATES, templates);
      
      if (!result.success) {
        throw new Error(result.error || '保存模板失败');
      }

      console.log('[ExportService] 模板保存成功:', template.name);
    } catch (error) {
      console.error('[ExportService] 保存导出模板失败:', error);
      throw error;
    }
  }

  /**
   * 获取导出模板
   */
  async getExportTemplates(format?: 'pdf' | 'word'): Promise<ExportTemplate[]> {
    try {
      const result = await simpleStorageAdapter.get<ExportTemplate[]>(EXPORT_STORAGE_KEYS.CUSTOM_TEMPLATES);
      
      let templates: ExportTemplate[] = [];
      
      if (result.success && result.data) {
        templates = result.data;
      }

      // 添加默认模板
      templates = [...this.getDefaultTemplates(), ...templates];

      // 按格式筛选
      if (format) {
        templates = templates.filter(t => t.format === format);
      }

      return templates.sort((a, b) => {
        // 默认模板排在前面
        if (a.isDefault && !b.isDefault) return -1;
        if (!a.isDefault && b.isDefault) return 1;
        return a.name.localeCompare(b.name);
      });
    } catch (error) {
      console.error('[ExportService] 获取导出模板失败:', error);
      return this.getDefaultTemplates();
    }
  }

  /**
   * 删除导出模板
   */
  async deleteExportTemplate(templateId: string): Promise<void> {
    try {
      const templates = await this.getExportTemplates();
      const filteredTemplates = templates.filter(t => t.id !== templateId && !t.isDefault);

      const result = await simpleStorageAdapter.set(EXPORT_STORAGE_KEYS.CUSTOM_TEMPLATES, filteredTemplates);
      
      if (!result.success) {
        throw new Error(result.error || '删除模板失败');
      }

      console.log('[ExportService] 模板删除成功:', templateId);
    } catch (error) {
      console.error('[ExportService] 删除导出模板失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户保存的PDF设置
   */
  async getUserPDFSettings(): Promise<Partial<PDFExportOptions>> {
    try {
      const result = await simpleStorageAdapter.get<Partial<PDFExportOptions>>(EXPORT_STORAGE_KEYS.PDF_SETTINGS);
      return result.success && result.data ? result.data : {};
    } catch (error) {
      console.error('[ExportService] 获取PDF设置失败:', error);
      return {};
    }
  }

  /**
   * 保存用户PDF设置
   */
  async saveUserPDFSettings(settings: Partial<PDFExportOptions>): Promise<void> {
    try {
      const result = await simpleStorageAdapter.set(EXPORT_STORAGE_KEYS.PDF_SETTINGS, settings);
      if (!result.success) {
        throw new Error(result.error || '保存PDF设置失败');
      }
    } catch (error) {
      console.error('[ExportService] 保存PDF设置失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户保存的Word设置
   */
  async getUserWordSettings(): Promise<Partial<WordExportOptions>> {
    try {
      const result = await simpleStorageAdapter.get<Partial<WordExportOptions>>(EXPORT_STORAGE_KEYS.WORD_SETTINGS);
      return result.success && result.data ? result.data : {};
    } catch (error) {
      console.error('[ExportService] 获取Word设置失败:', error);
      return {};
    }
  }

  /**
   * 保存用户Word设置
   */
  async saveUserWordSettings(settings: Partial<WordExportOptions>): Promise<void> {
    try {
      const result = await simpleStorageAdapter.set(EXPORT_STORAGE_KEYS.WORD_SETTINGS, settings);
      if (!result.success) {
        throw new Error(result.error || '保存Word设置失败');
      }
    } catch (error) {
      console.error('[ExportService] 保存Word设置失败:', error);
      throw error;
    }
  }

  /**
   * 添加到导出历史
   */
  private async addToHistory(item: ExportHistoryItem): Promise<void> {
    try {
      const history = await this.getExportHistory();
      
      // 添加新记录到开头
      history.unshift(item);
      
      // 限制历史记录数量（最多100条）
      const limitedHistory = history.slice(0, 100);

      const result = await simpleStorageAdapter.set(EXPORT_STORAGE_KEYS.EXPORT_HISTORY, limitedHistory);
      
      if (!result.success) {
        console.error('[ExportService] 保存导出历史失败:', result.error);
      }
    } catch (error) {
      console.error('[ExportService] 添加导出历史失败:', error);
    }
  }

  /**
   * 获取默认模板
   */
  private getDefaultTemplates(): ExportTemplate[] {
    const now = Date.now();
    
    return [
      {
        id: 'default-pdf-standard',
        name: '标准PDF模板',
        format: 'pdf',
        isDefault: true,
        options: {
          format: 'A4',
          orientation: 'portrait',
          margins: { top: 20, right: 20, bottom: 20, left: 20 },
          fontSize: 12,
          fontFamily: 'SimSun, serif',
          includeMetadata: true,
          quality: 'medium'
        } as PDFExportOptions,
        createdAt: now,
        updatedAt: now
      },
      {
        id: 'default-pdf-presentation',
        name: '演示PDF模板',
        format: 'pdf',
        isDefault: true,
        options: {
          format: 'A4',
          orientation: 'landscape',
          margins: { top: 15, right: 15, bottom: 15, left: 15 },
          fontSize: 14,
          fontFamily: 'SimHei, sans-serif',
          includeMetadata: true,
          quality: 'high'
        } as PDFExportOptions,
        createdAt: now,
        updatedAt: now
      },
      {
        id: 'default-word-standard',
        name: '标准Word模板',
        format: 'word',
        isDefault: true,
        options: {
          template: 'standard',
          fontSize: 12,
          fontFamily: 'SimSun',
          lineSpacing: 1.5,
          margins: { top: 25.4, right: 25.4, bottom: 25.4, left: 25.4 },
          includeTableOfContents: false
        } as WordExportOptions,
        createdAt: now,
        updatedAt: now
      },
      {
        id: 'default-word-formal',
        name: '正式Word模板',
        format: 'word',
        isDefault: true,
        options: {
          template: 'formal',
          fontSize: 14,
          fontFamily: 'SimSun',
          lineSpacing: 2.0,
          margins: { top: 30, right: 25, bottom: 25, left: 30 },
          includeTableOfContents: true,
          headerFooter: {
            footer: '第 {PAGE} 页 共 {NUMPAGES} 页'
          }
        } as WordExportOptions,
        createdAt: now,
        updatedAt: now
      }
    ];
  }

  /**
   * 生成唯一ID
   */
  private generateId(): string {
    return `export_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}

// 导出服务单例
let exportServiceInstance: ExportServiceImpl | null = null;

export function createExportService(progressCallback?: (progress: ExportProgress) => void): ExportServiceImpl {
  if (!exportServiceInstance) {
    exportServiceInstance = new ExportServiceImpl(progressCallback);
  }
  return exportServiceInstance;
}

export const exportService = createExportService();